package org.sakai.controller;

import org.sakai.entity.ApiResponseEntity;
import org.sakai.entity.Message;
import org.sakai.entity.Result;
import org.sakai.service.MessageService;
import org.sakai.service.ConsultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private MessageService messageService;
    
    @Autowired
    private ConsultService consultService;

    /**
     * 获取问诊聊天消息列表
     * @param orderId 订单ID
     * @param lastTime 最后一条消息时间
     * @return 消息列表
     */
    @GetMapping("/order/{orderId}/messages")
    public ResponseEntity<List<Map<String, Object>>> getChatMessageList(
            @PathVariable String orderId,
            @RequestParam(required = false) String lastTime) {
        
        Result<List<Map<String, Object>>> result = messageService.getChatMessageList(orderId, lastTime);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 发送聊天消息
     * @param messageRequest 消息请求体
     * @return 发送结果
     */
    @PostMapping("/message/send")
    public ResponseEntity<Message> sendChatMessage(@RequestBody Map<String, Object> messageRequest) {
        String orderId = (String) messageRequest.get("orderId");
        Integer msgType = (Integer) messageRequest.get("msgType");
        String content = (String) messageRequest.get("content");
        String fromUser = messageRequest.get("fromUser").toString(); // 实际应该从认证信息中获取
        String toUser = messageRequest.get("toUser").toString();    // 实际应该根据订单信息获取医生ID
        
        // 处理图片消息
        String pictureId = null;
        Map<String, Object> picture = (Map<String, Object>) messageRequest.get("picture");
        if (picture != null) {
            pictureId = (String) picture.get("id");
        }
        
        Result<Message> result = messageService.sendChatMessage(orderId, msgType, content, pictureId, fromUser, toUser);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 更新消息状态为已读
     * @param messageId 消息ID
     * @return 更新结果
     */
    @PutMapping("/message/{messageId}/read")
    public ResponseEntity<String> updateMessageStatus(@PathVariable String messageId) {
        Result<String> result = messageService.updateMessageStatus(messageId);
        return ApiResponseEntity.getResponseEntity(result);
    }
    
    /**
     * 获取最新消息
     * @param consultId 问诊ID
     * @return 最新消息
     */
    @GetMapping("/latest-message/{consultId}")
    public ResponseEntity<Message> getLatestMessage(@PathVariable String consultId) {
        Result<Message> result = messageService.getLatestMessage(consultId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 获取用户的消息列表（类似微信聊天列表）
     * @param userId 用户ID
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @param sortByUnread 是否按未读数量排序
     * @return 消息列表
     */
    @GetMapping("/message-list/{userId}")
    public ResponseEntity<Map<String, Object>> getMessageList(
            @PathVariable String userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "true") Boolean sortByUnread) {
        Result<Map<String, Object>> result = messageService.getMessageList(userId, page, size, sortByUnread);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 获取用户头像
     * @param userId 用户ID
     * @return 头像URL
     */
    @GetMapping("/user/avatar/{userId}")
    public ResponseEntity<String> getUserAvatar(@PathVariable String userId) {
        Result<String> result = messageService.getUserAvatar(userId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 获取未读消息数量
     * @param userId 用户ID
     * @return 未读消息数量
     */
    @GetMapping("/unread-count/{userId}")
    public ResponseEntity<Integer> getUnreadMessageCount(@PathVariable String userId) {
        Result<Integer> result = messageService.getUnreadMessageCount(userId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 获取指定会话的未读消息数量
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 未读消息数量
     */
    @GetMapping("/unread-count/{consultId}/{userId}")
    public ResponseEntity<Integer> getUnreadMessageCountByConsult(
            @PathVariable String consultId, 
            @PathVariable String userId) {
        Result<Integer> result = messageService.getUnreadMessageCountByConsult(consultId, userId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 标记指定会话的所有消息为已读
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 操作结果
     */
    @PutMapping("/mark-read/{consultId}/{userId}")
    public ResponseEntity<String> markMessagesAsRead(
            @PathVariable String consultId, 
            @PathVariable String userId) {
        Result<String> result = messageService.markMessagesAsRead(consultId, userId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 获取会话信息（包含最新消息、未读数等）
     * @param consultId 问诊ID
     * @param userId 用户ID
     * @return 会话信息
     */
    @GetMapping("/conversation/{consultId}/{userId}")
    public ResponseEntity<Map<String, Object>> getConversationInfo(
            @PathVariable String consultId, 
            @PathVariable String userId) {
        Result<Map<String, Object>> result = messageService.getConversationInfo(consultId, userId);
        return ApiResponseEntity.getResponseEntity(result);
    }

    /**
     * 清除用户所有未读消息
     * @param userId 用户ID
     * @return 操作结果
     */
    @PutMapping("/clear-all-unread/{userId}")
    public ResponseEntity<String> clearAllUnreadMessages(@PathVariable String userId) {
        Result<String> result = messageService.clearAllUnreadMessages(userId);
        return ApiResponseEntity.getResponseEntity(result);
    }
}
